package com.zlw.framework.web.handler;

import com.zlw.framework.beans.BeanFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName MappingHandler
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2020/1/28  19:03
 * @Version 1.0
 */

//请求映射器
public class MappingHandler {

    private String uri;
    private Method method;//反射包这个类
    private Class<?> controller;
    //调用方法所需的参数
    private String[] agrs;


    public MappingHandler(String uri, Method method, Class<?> controller, String[] agrs) {
        this.uri = uri;
        this.method = method;
        this.controller = controller;
        this.agrs = agrs;
    }


    public boolean handle(ServletRequest req, ServletResponse res) throws IllegalAccessException, InstantiationException, InvocationTargetException, IOException {
        //先 判断 次 handler 能不能 处理这个 uri
        String reqUri = ((HttpServletRequest) req).getRequestURI();
        //判断 handler 里面的 uri 跟 请求的uri 是否是一个
        if (!uri.equals(reqUri)) {
            return false;
        }
        //准备一下参数
        Object[] parameters = new Object[agrs.length];
        for (int i = 0; i < agrs.length; i++) {
            parameters[i] = req.getParameter(agrs[i]);
        }

        //此处有修改
        //Object ctl = controller.newInstance();
        Object ctl = BeanFactory.getBean(controller);
        Object response = method.invoke(ctl, parameters);
        //把  方法 返回的结果 返到 response中
        System.out.println("--> "+response.toString());
        res.getWriter().println(response.toString());

        return true;
    }
}
